package com.gp.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gp.tms.pojo.LoginUser;
import com.gp.tms.pojo.User;
import com.gp.tms.mapper.UserMapper;
import com.gp.tms.pojo.dto.LoginDto;
import com.gp.tms.service.IUserRoleService;
import com.gp.tms.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gp.tms.utils.Assert;
import com.gp.tms.utils.JwtUtil;
import com.gp.tms.utils.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author team
 * @since 2023-03-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public UserDetails getLoginUserByUsername(String username) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user == null) {
            return null;
        }

        List<String> permissions =  new ArrayList<>();
        return new LoginUser(user, permissions);
    }

    @Override
    public RespBean<Map<String, String>> userLogin(LoginDto loginDto, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (captcha == null || !captcha.equalsIgnoreCase(loginDto.getCaptcha())) {
            return RespBean.error("验证码不正确");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginDto.getUsername());
        if (!passwordEncoder.matches(loginDto.getPassword(), userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确");
        }

        if (!userDetails.isEnabled()) {
            return RespBean.error("账户被禁用，请联系管理员");
        }

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = jwtUtil.generateToken(userDetails);
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("token", token);
        return RespBean.success("登陆成功", tokenMap);
    }
}
